package com.scproject.scbef.service.study.politicsknowledge.impl;

import com.scproject.dto.ResponseDto;
import com.scproject.scbef.exception.ProcessException;
import com.scproject.scbef.mapper.ImgMapper;
import com.scproject.scbef.mapper.ImgRelationMapper;
import com.scproject.scbef.mapper.PoliticsKnowledgeMapper;
import com.scproject.scbef.mapper.PoliticsKnowledgeTypeMapper;
import com.scproject.scbef.pojo.Img;
import com.scproject.scbef.pojo.ImgRelation;
import com.scproject.scbef.pojo.PoliticsKnowledge;
import com.scproject.scbef.pojo.PoliticsKnowledgeExample;
import com.scproject.scbef.pojo.expandenum.ImgTypeEnum;
import com.scproject.scbef.pojo.vo.PoliticsKnowledgeVo;
import com.scproject.scbef.pojo.vo.ResponseCodeEnum;
import com.scproject.scbef.service.study.politicsknowledge.PoliticsKnowLedgeService;
import com.scproject.utils.FtpFileUtil;
import com.scproject.utils.JWTUtils;
import com.scproject.utils.ProcessFileUtils;
import com.scproject.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Response;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.scproject.utils.ProcessFileUtils.processFile;

/**
 * @author LNL
 * @date 2021/5/25 19:30
 */
@Service("politicsKnowLedgeService")
public class PoliticsKnowLedgeServiceImpl implements PoliticsKnowLedgeService {

    @Autowired
    private PoliticsKnowledgeMapper politicsKnowledgeMapper;

    @Autowired
    private ImgRelationMapper imgRelationMapper;

    @Autowired
    private ImgMapper imgMapper;


    @Override
    public ResponseDto getAllPoliticsKnowledge() {
        ResponseDto responseDto = null;
        List<PoliticsKnowledgeVo> politicsKnowledges = politicsKnowledgeMapper.selectAllPoliticsKnowledge(ImgTypeEnum.POLITICS_KNOWLEDGE.toString());
        Optional<List<PoliticsKnowledgeVo>> optionalPoliticsKnowledges = Optional.ofNullable(politicsKnowledges);
        if(optionalPoliticsKnowledges.isPresent()) {
            responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(),"党建知识",politicsKnowledges);
        }else {
            responseDto = new ResponseDto(ResponseCodeEnum.ERROR.toString(),"数据获取失败",politicsKnowledges);
        }
        return responseDto;
    }

    @Override
    public ResponseDto deletePoliticsKnowledge(String id, HttpServletRequest request) {
        //逻辑，删除了校园新闻之后，需要删除图片的关联
        ResponseDto responseDto = null;
        int isDelete = politicsKnowledgeMapper.deleteByPrimaryKey(id);
        int isDeleteImgRe = imgRelationMapper.deleteByRelationId(id, ImgTypeEnum.SCHOOL_NEWS.toString());
        //删除id这条记录
        if (isDelete > 0) {
            responseDto = new ResponseDto("1000", "删除成功");
        } else {
            throw new ProcessException("删除失败,id无效,请重试");
        }
        return responseDto;
    }

    @Override
    public ResponseDto insertPoliticsKnowledge(MultipartHttpServletRequest request) {

        ResponseDto responseDto = null;
        //获取用户
        Map<String, String> userInfo = JWTUtils.getInfo(request.getHeader("token"));
        try {
            //获取到参数
            Map<String, String[]> dataInfo = request.getParameterMap();
            //时间格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            PoliticsKnowledge politicsKnowledge = new PoliticsKnowledge();
            politicsKnowledge.setId(UUIDUtils.getUUID());
            politicsKnowledge.setContent(dataInfo.get("content")[0]);
            politicsKnowledge.setTitle(dataInfo.get("title")[0]);
            try {
                politicsKnowledge.setPublishTime(sdf.parse(dataInfo.get("publishTime")[0]));
            } catch (ParseException e) {
                throw new ProcessException("时间格式问题");
            }
            politicsKnowledge.setCreateUser(userInfo.get("userId"));
            politicsKnowledge.setCreateTime(new Date());


            int isInsertKnowledge = politicsKnowledgeMapper.insertSelective(politicsKnowledge);
            if(isInsertKnowledge > 0) {
                List<MultipartFile> files = request.getFiles("file_transfer");
                for (MultipartFile file : files) {
                    Map<String, String> fileData = ProcessFileUtils.processFile(file);
                    //将图片存放到数据库中
                    Img img = new Img();
                    img.setId(UUIDUtils.getUUID());
                    img.setName(fileData.get("fileName"));
                    img.setPath(fileData.get("filePath"));

                    ImgRelation imgRelation = new ImgRelation();
                    imgRelation.setId(UUIDUtils.getUUID());
                    imgRelation.setImgId(img.getId());
                    imgRelation.setRelationId(politicsKnowledge.getId());
                    imgRelation.setType(ImgTypeEnum.POLITICS_KNOWLEDGE.toString());

                    int isInsertImg = imgMapper.insertSelective(img);
                    int isInsertImgRelation = imgRelationMapper.insertSelective(imgRelation);

                    if(isInsertImg > 0 && isInsertImgRelation > 0) {
                        responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(),"添加成功");
                    }else {
                        throw new ProcessException("添加失败");
                    }
                }
            }else {
                throw new ProcessException("添加失败");
            }
        } catch (Exception e) {
            throw new ProcessException("添加失败,请注意时间格式");
        }
        return responseDto;
    }

    @Override
    public ResponseDto updatePoliticsKnowledge(PoliticsKnowledge politicsKnowledge, HttpServletRequest request) {
        ResponseDto responseDto = null;
        Map<String, String> userInfo = JWTUtils.getInfo(request.getHeader("token"));
        politicsKnowledge.setEditUser(userInfo.get("userId"));
        politicsKnowledge.setEditTime(new Date());

        int isUpdate = politicsKnowledgeMapper.updateByPrimaryKeySelective(politicsKnowledge);
        if(isUpdate > 0) {
            responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(),"更新成功");
        }else {
            throw new ProcessException("更新失败");
        }
        return responseDto;
    }

}
